﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.DBUtility;
using System.Data.SqlClient;
public partial class Hospital_PurchaseDeal_detail : System.Web.UI.Page
{

    string strSql, Accountid_yy, buystate;
    ArrayList ArryBuyPlanGoodsid = new ArrayList();
    public string tempid, BuyPlanId = "";

    /// <summary>
    /// Page_Load
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        BuyPlanId = SysFun.IsSQL(SysFun.ToTrim(Request.QueryString["BuyPlanId"]));

        System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
        _AccountType.Add(HZ.MBSM.DAL.AccountType.enumHospitale);

        if (HZ.MBSM.BLL.Login.CheckAssert(_AccountType))
        {

            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            Accountid_yy = SysFun.ToTrim(_Account.AccountId);
            LabHospital.Text = _Account.DWName;
            if (!IsPostBack)
            {

                CopyPurchasePlan();//绑定采购单

                labSubmit.Text = "";
                labDel.Text = "<input type='submit' name='btnSubmit' value='删除' class='button_bg'   onclick=\"javascript:return confirm('确定真的要删除吗？？？？ ');\" id='Submit3'/>";

                Db db = new Db();
                System.Data.IDataReader dr;
                strSql = "select * from PurchasePlan where BuyPlanId=" + BuyPlanId + " and AccountId_YY=" + _Account.AccountId;
                dr = db.DataReader(strSql);

                if (dr.Read())
                {
                    txtStartTime.Text = Convert.ToDateTime(dr["StartTime"]).ToShortDateString();
                    txtEndTime.Text = Convert.ToDateTime(dr["EndTime"]).ToShortDateString();
                    txtPlanName.Text = SysFun.ToTrim(dr["PlanName"]);
                    rdoBuyStatus.SelectedValue = SysFun.ToTrim(dr["BuyStatus"]);
                    txtRemarks.Text = SysFun.ToTrim(dr["Remarks"]);
                    buystate = SysFun.ToTrim(dr["BuyStatus"]);
                    ViewState["buystateg"] = buystate;
                    if (buystate == "2")
                    {

                        labLink.Visible = false;
                        labDel.Visible = false;
                        labSubmit.Visible = false;

                    }
                    if (SysFun.ToInt(dr["BuyStatus"]) == 1 || SysFun.ToInt(dr["BuyStatus"]) == 0)
                    {

                    }
                }
                else
                {
                    Response.Write("对不起，你没有权限浏览不属于自身采购单的药品");
                    dr.Close();
                    dr.Dispose();
                    db.Close();
                    return;
                }
                dr.Close();
                dr.Dispose();
                db.Close();
                FinBuyPlanGoods();
                showGridView();

            }

            if (Request.Form["PullPruList"] == "提交采购单")
            {

                string str;

                str = "select count(*) as cum from BuyPlanGoods where BuyPlanId =" + BuyPlanId;
                Db db = new Db();
                System.Data.IDataReader dr;
                dr = db.DataReader(str);
                if (dr.Read())
                {
                    if (Convert.ToInt32(dr["cum"]) <= 0)
                    {
                        Response.Write("<script>window.alert('对不起，你还未采购药品，不能提交采购单');window.history.back(0);</script>");
                        dr.Close();
                        dr.Dispose();
                        db.Close();
                        dr = null;
                        db = null;
                        return;
                    }

                }

                dr.Close();
                dr.Dispose();
                str = "select GoodsNum from BuyPlanGoods where (GoodsNum=0 or GoodsNum='' or GoodsNum is null)  and buyplanid=" + BuyPlanId;
                dr = db.DataReader(str);
                if (dr.Read())
                {
                    Response.Write("<script>window.alert('对不起，有采购量为0的药品，不能提交采购单');window.history.back(0);</script>");
                    dr.Close();
                    dr.Dispose();
                    db.Close();
                    dr = null;
                    db = null;
                    return;
                }
                dr.Close();
                dr.Dispose();
                str = "update PurchasePlan set BuyStatus='2',PurchasePlanDate=getdate() where BuyPlanId=" + BuyPlanId;
                db.Command(str);
                db.Close();
                HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "PurchasePlan", str, "../Hospital/PurchaseDeal_detail.aspx");
                Response.Write("<script>window.alert('提交成功');window.opener.location.reload();window.close();</script>");

            }

            if (Request.Form["btnSubmit"] == "删除" && Request.Form["chk"] != null)
            {
                string BuyPlanGoodsId = "";
                BuyPlanGoodsId = SysFun.ToTrim(Request.Form["chk"]);
                Db db = new Db();
                if (buystate == "2")
                {
                    Response.Write("<script>window.alert('对不起，采购单已经提交给配送人，不可删除！');</script>");
                }
                else
                {
                    if (BuyPlanGoodsId != "")
                    {
                        string[] BGID = BuyPlanGoodsId.Length == 0 ? new string[] { "" } : BuyPlanGoodsId.Substring(0).Split(new char[] { ',' });

                        strSql = "";
                        for (int i = 0; i < BGID.Length; i++)
                        {
                            if (ViewState["buystateg"].Equals("1")) //已采购未提交
                            {
                                strSql += "@" + "delete  from BuyPlanGoods  where BuyPlanGoodsId=" + BGID[i].ToString() + " and dealstatus<>2 ";
                            }
                            else if (ViewState["buystateg"].Equals("2")) //已提交
                            {
                                strSql += "@" + "update BuyPlanGoods  set dealstatus=6 where BuyPlanGoodsId=" + BGID[i].ToString() + " and (dealstatus=0 or dealstatus=5)";
                            }
                        }
                        if (strSql.Length > 0)
                        {
                            db.ExecuteTransaction(strSql.Substring(1).Split(new char[] { '@' }), 30);
                            HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "删除", "BuyPlanGoods", strSql, "../Hospital/PurchaseDeal_detail.aspx");
                        }
                    }

                }
                db.Close();
                db = null;
                showGridView();

            }
            if (Request.Form["butSave"] == "保存采购价和采购量")
            {
                string BuyPlanGoodsId = "", jiaoyijia, BidPrice, caigoushu, _strGoodsId;
                string _GoodsId = "", _strAccountid_PS, _strSupplyGoodsId, _strTradePrice = "", _strGoodsNum = "", _strinflow = "";
                BuyPlanGoodsId = SysFun.ToTrim(Request.Form["buyplangoodsid"]);
                jiaoyijia = Request.Form["TradePrice"];
                BidPrice = Request.Form["BidPrice"];
                caigoushu = Request.Form["GoodsNum"];
                _strGoodsId = SysFun.ToTrim(Request.Form["hidGoodsId"]);
                _strAccountid_PS = Request.Form["AccountId_PS"].ToString();
                _strSupplyGoodsId = Request.Form["SupplyGoodsId"].ToString();
                _strTradePrice = Request.Form["oldTradePrice"] == "" ? "" : Request.Form["oldTradePrice"].ToString();//医院采购价
                _strGoodsNum = Request.Form["oldGoodsNum"] == "" ? "" : Request.Form["oldGoodsNum"].ToString(); //医院采购量
                _strinflow = Request.Form["InflowNum"] == "" ? "" : Request.Form["InflowNum"].ToString();  //企业确认量
                string _pricestatus = Request.Form["pricestatus"];
                Db db = new Db();
                //是否已提交

                if (buystate == "2")
                {
                    db.Close();
                    Response.Write("<script>window.alert('对不起，采购单已经提交给配送人，不可修改交易价！');</script>");
                }
                else
                {

                    string[] SGID = BuyPlanGoodsId.Length == 0 ? new string[] { "" } : BuyPlanGoodsId.Substring(0).Split(new char[] { ',' });
                    string[] TPrice = jiaoyijia.Length == 0 ? new string[] { "" } : jiaoyijia.Substring(0).Split(new char[] { ',' });
                    string[] BPrice = BidPrice.Length == 0 ? new string[] { "" } : BidPrice.Substring(0).Split(new char[] { ',' });
                    string[] CNum = caigoushu.Length == 0 ? new string[] { "" } : caigoushu.Substring(0).Split(new char[] { ',' });
                    string[] _strArrayGoodsId = _strGoodsId.Length == 0 ? new string[] { "" } : _strGoodsId.Substring(0).Split(new char[] { ',' });
                    string[] Accountid_PS = _strAccountid_PS.Length == 0 ? new string[] { "" } : _strAccountid_PS.Substring(0).Split(new char[] { ',' });
                    string[] strSupplyGoodsId = _strSupplyGoodsId.Length == 0 ? new string[] { "" } : _strSupplyGoodsId.Substring(0).Split(new char[] { ',' });
                    string[] GoodsNum = _strGoodsNum.Length == 0 ? new string[] { "" } : _strGoodsNum.Substring(0).Split(new char[] { ',' });
                    string[] oldTradePrice = _strTradePrice.Length == 0 ? new string[] { "" } : _strTradePrice.Substring(0).Split(new char[] { ',' });
                    string[] oldGoodsNum = _strGoodsNum.Length == 0 ? new string[] { "" } : _strGoodsNum.Substring(0).Split(new char[] { ',' });
                    string[] Stringflow = _strinflow.Length == 0 ? new string[] { "" } : _strinflow.Substring(0).Split(new char[] { ',' });
                    string[] pricestatus_arry = _pricestatus.Length == 0 ? new string[] { "" } : _pricestatus.Substring(0).Split(new char[] { ',' });

                    int nNumber = 0;
                    strSql = "";
                    for (int i = 0; i < SGID.Length; i++)
                    {

                        if (pricestatus_arry[i] == "0" || pricestatus_arry[i] == "1")
                        {
                            if ((TPrice[i] != "") && (Convert.ToDouble(TPrice[i]) > Convert.ToDouble(BPrice[i])))
                            {
                                Response.Write("<script>alert('流水号" + _strArrayGoodsId[i].ToString() + "交易价不能大于挂网价！');</script>");
                                continue;
                            }
                        }


                        if (((CNum[i] == "") || (Convert.ToInt32(CNum[i]) == 0)) && (Convert.ToDouble(TPrice[i]) != Convert.ToDouble(oldTradePrice[i])))
                        {
                            _GoodsId += _strArrayGoodsId[i].ToString() + " ";
                        }
                        else
                        {

                            if ((SGID[i] != "") && (CNum[i] != "") && (TPrice[i] != "") && (Convert.ToDouble(TPrice[i]) != 0.0))
                            {
                                if ((Convert.ToDouble(TPrice[i]) != Convert.ToDouble(oldTradePrice[i])) || (Convert.ToDouble(CNum[i]) != Convert.ToDouble(oldGoodsNum[i])))
                                {
                                    //在企业已确认的情况下 修改数量不能改大， 不能改小于企业确认价 
                                    if (String.IsNullOrEmpty(Stringflow[1]))//企业确认数为空 这种事 1.未确认送货 2.医院已删除 只有在 未确认送货下可以修改
                                    {
                                        strSql += "@" + "update BuyPlanGoods set TradePrice=" + TPrice[i] + ",GoodsNum=" + SysFun.ToInt(CNum[i]) + ",PurchasePrice=" + SysFun.ToDouble(TPrice[i]) * SysFun.ToInt(CNum[i]) + ",dealstatus=(case when " + SysFun.ToInt(CNum[i]) + "=0 then 6 else dealstatus end) where BuyPlanGoodsId=" + SGID[i].ToString() + " and DealStatus=0 ";
                                    }
                                    else                          //企业确认有数据 中情况 1.确认送货（可修改但不能大原来值不能小于企业值）2 入库了（不能修改）3 无法送货（不能改）
                                    {    //就是 修改值小于原来采购值 大于或等于企业确认值
                                        if ((Convert.ToDouble(CNum[i]) < Convert.ToDouble(oldGoodsNum[i])) && (Convert.ToDouble(CNum[i]) >= Convert.ToDouble(Stringflow[i])))
                                        {
                                            strSql += "@" + "update BuyPlanGoods set TradePrice=" + TPrice[i] + ",GoodsNum=" + SysFun.ToInt(CNum[i]) + ",PurchasePrice=" + SysFun.ToDouble(TPrice[i]) * SysFun.ToInt(CNum[i]) + ",dealstatus=(case when " + SysFun.ToInt(CNum[i]) + "=0 then 6 else dealstatus end) where BuyPlanGoodsId=" + SGID[i].ToString() + " and DealStatus=1 ";
                                        }
                                    }
                                }
                            }

                            nNumber++;
                        }

                    }
                    if ((strSql.Length > 0) && (nNumber == SGID.Length))
                    {
                        db.ExecuteTransaction(strSql.Substring(1).Split(new char[] { '@' }), 30);
                        HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新，插入", "BuyPlanGoods", strSql, "../Hospital/PurchaseDeal_detail.aspx");
                        Response.Write("<script>alert('保存成功！');</script>");
                    }
                    else
                    {
                        if (_GoodsId != "")
                        {
                            Response.Write("<script>alert('流水号为" + _GoodsId + "的价格做了修改但采购量为0，请填写或删除！');</script>");
                        }
                    }

                    db.Close();
                }
            }
            showGridView();
            //Db db1 = new Db();
            //IDataReader dr1 = db1.DataReader("select pricestatus from project where projectid=" + Request.QueryString["projectid"].ToString());
            //if (dr1.Read())
            //{
            //    tempid = dr1["pricestatus"].ToString();
            //}
            //dr1.Close();
            //db1.Close();

            labLink.Text = "<a target='_blank' href='PurchaseGoods.aspx?BuyPlanId=" + BuyPlanId + "&projectid=" + SysFun.RequestEncrypt(Request.QueryString["projectid"].ToString()) + "'><img style='border-top-style: none; border-right-style: none; border-left-style: none; border-bottom-style: none' src='../Images/zjcg.gif' /></a> ";
            labSubmit.Text = "<input id=\"Submit1\" type=\"submit\" value=\"提交采购单\" name=\"PullPruList\" onclick=\"javascript:return confirm('确认将该采购单提交给配送人吗？提交后无法修改和新增采购药品');\" class=\"button_bg6\" style=\"width: 90px\" />";
            labSave.Text = "<input  type='submit' name='butSave' class='button_bg8'  style='width:121px' value='保存采购价和采购量' />（请在提交采购单和打印明细前点击此按钮）";

        }
    }

    /// <summary>
    /// 根据BuyPlanId 得到采购单中的BuyPlanGoodsid
    /// </summary>
    private void FinBuyPlanGoods()
    {

        if (BuyPlanId == "") return;
        string strSelect = "select BuyPlanGoodsid  from BuyPlanGoods where BuyPlanId=" + BuyPlanId;
        Db db = new Db();
        System.Data.IDataReader dr = db.DataReader(strSelect);
        while (dr.Read())
        {

            ArryBuyPlanGoodsid.Add(dr["BuyPlanGoodsid"]);

        }

        dr.Close();
        dr.Dispose();
        db.Close();

    }

    /// <summary>
    /// 显示GridView数据
    /// </summary>
    public void showGridView()
    {

        int i = 0;
        Db db = new Db();
        DbPage dbPage = new DbPage(db);

        dbPage.Table = "BuyGoodsView_200708,project";
        dbPage.Key = "BuyPlanGoodsId";

        //表的主键    
        dbPage.Where = strcheck(0);                                                  //查询条件  
        if ((string)ViewState["buystateg"] == "2")
        {
            // dbPage.SelectField = " pricestatus,AccountId_PS, BuyPlanGoodsId,InflowNum,GoodsNum,isnull(TradePrice,purchaseprice) as TradePrice,Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '送货中' WHEN '2' then '已入库' WHEN '3' then '退货' When '4' Then '企业无法送货' When '5' Then '已确认但到期未送货' When '6' Then '已删除' END AS DealStatus,BidPrice,PurchasePrice,SupplyGoodsId,GoodsId,ProductCode,ProductName,MedicineModel,Outlookc,Factor,CompanyName_SC,CompanyName_TB,CompanyName_PS,case GoodsState when 0 then '原挂网'  when 1 then '自行采购'  when 2 then '22种降价'  when 3 then '血液制品'  when 4 then '重点监控' end as GoodsState,GoodsName,IsNull(Unit,'')+'/'+IsNull(PackUnit,'') As Pack1,case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " END AS QualityLevels,case when EndTime>getdate() then 1 else 2 end as timeout";//要显示的字段
            dbPage.SelectField = " pricestatus,AccountId_PS,remark,BuyPlanGoodsId,InflowNum,GoodsNum,isnull(TradePrice,purchaseprice) as TradePrice,Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '送货中' WHEN '2' then '已入库' WHEN '3' then '退货' When '4' Then '企业无法送货' When '5' Then '已确认但到期未送货' When '6' Then '已删除' END AS DealStatus,BidPrice,PurchasePrice,SupplyGoodsId,GoodsId,ProductCode,ProductName,MedicineModel,Outlookc,Factor,CompanyName_SC,CompanyName_TB,CompanyName_PS,GoodsName,Outlookc+'×'+convert(varchar(20),Factor)+unit As Pack1,case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " END AS QualityLevels,case when EndTime>getdate() then 1 else 2 end as timeout";//要显示的字段
        }
        else
        {
            // dbPage.SelectField = " pricestatus,AccountId_PS, BuyPlanGoodsId,InflowNum,GoodsNum,isnull(TradePrice,purchaseprice) as TradePrice,Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '送货中' WHEN '2' then '已入库' WHEN '3' then '退货' When '4' Then '企业无法送货' When '5' Then '已确认但到期未送货'  When '6' Then '已删除' END AS DealStatus,BidPrice,PurchasePrice,SupplyGoodsId,GoodsId,ProductCode,ProductName,MedicineModel,Outlookc,Factor,CompanyName_SC,CompanyName_TB,CompanyName_PS,case GoodsState when 0 then '原挂网'  when 1 then '自行采购'  when 2 then '22种降价'  when 3 then '血液制品'  when 4 then '重点监控' end as GoodsState,GoodsName,IsNull(Unit,'')+'/'+IsNull(PackUnit,'') As Pack1,case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + "  END AS QualityLevels,case when EndTime>getdate() then 1 else 2 end as timeout";//要显示的字段
            dbPage.SelectField = " pricestatus,AccountId_PS,remark,BuyPlanGoodsId,InflowNum,GoodsNum,isnull(TradePrice,purchaseprice) as TradePrice,Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '送货中' WHEN '2' then '已入库' WHEN '3' then '退货' When '4' Then '企业无法送货' When '5' Then '已确认但到期未送货'  When '6' Then '已删除' END AS DealStatus,BidPrice,PurchasePrice,SupplyGoodsId,GoodsId,ProductCode,ProductName,MedicineModel,Outlookc,Factor,CompanyName_SC,CompanyName_TB,CompanyName_PS,GoodsName,Outlookc+'×'+convert(varchar(20),Factor)+unit As Pack1,case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + "  END AS QualityLevels,case when EndTime>getdate() then 1 else 2 end as timeout";//要显示的字段
        }
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        dbPage.PageSize = 20;                                                    //没有显示记录条数   
        dbPage.OrderBy = "goodsid,ProductName,MedicineModel";//排序字段
        System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
        strHtml.Append("<table width='100%'id='tabData22' border='0' align='right' cellpadding='2' cellspacing='1'>");
        strHtml.Append("<tr>");
        strHtml.Append("<td width='8%'>商品流水号</td>");
        strHtml.Append("<td  width='8%'>通用名</td>");
        strHtml.Append("<td  width='5%'>商品名</td>");
        strHtml.Append("<td  nowrap>剂型</td>");
        strHtml.Append("<td  nowrap>包装</td>");
        //strHtml.Append("<td  width='5%'>转换系数</td>");
        //strHtml.Append("<td  width='3%'>包装规格</td>");
        strHtml.Append("<td  >备注</td>");
        strHtml.Append("<td  >质量层次</td>");
        strHtml.Append("<td  >挂网价</td>");
        strHtml.Append("<td  >交易价</td>");
        strHtml.Append("<td  >采购量</td>");
        strHtml.Append("<td >企业确认数量</td>");
        strHtml.Append("<td  >采购总金额</td>");
        strHtml.Append("<td  width='9%'>生产企业</td>");
        strHtml.Append("<td  width='9%'>配送企业</td>");
        //  strHtml.Append("<td  >交易状态</td>");
        strHtml.Append("<td  >采购目录状态</td>");


        strHtml.Append("<td nowrap>选择</td>");
        strHtml.Append("</tr>");
        System.Data.IDataReader dr = dbPage.ExecuteReader();

        while (dr.Read())
        {
            int pricestatus = int.Parse((dr["pricestatus"].ToString())); // 0 固定,默认为挂网价  1  可修改,必须低于挂网价 2 可修改,无限制
            //tempid = dr["pricestatus"].ToString();
            string forecolor;
            switch (pricestatus)
            {
                case 0:  //  固定,默认为挂网价
                    forecolor = "#000000";
                    break;
                case 1:  //  可修改,必须低于挂网价

                    forecolor = "#990099";
                    break;
                case 2:  //  可修改,无限制

                    forecolor = "#0033CC";
                    break;
                default:
                    forecolor = "#000000";
                    break;
            }


            if (i == 0)
            {
                strHtml.Append("<tr class='table_td'>");
                i++;
            }
            else
            {
                strHtml.Append("<tr class='table_td2'>");
                i--;
            }
            strHtml.Append("<td style='color:" + forecolor + ";' width='8%'><input type='hidden' name='SupplyGoodsId' value='" + dr["SupplyGoodsId"].ToString() + "' /><input type='hidden' name='hidGoodsId' value='" + dr["GoodsId"].ToString() + "' />" + dr["GoodsId"].ToString() + "</td>");

            strHtml.Append("<td style='color:" + forecolor + ";' width='8%'>" + dr["ProductName"].ToString() + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";' width='5%'>" + dr["GoodsName"].ToString() + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";'>" + dr["Medicinemodel"].ToString() + "</td>");
            //  strHtml.Append("<td style='color:" + forecolor + ";'>" + dr["Outlookc"].ToString() + "×" + dr["Factor"].ToString() + dr["Pack1"].ToString() + "</td>");
            //strHtml.Append("<td style='color:" + forecolor + ";' width='5%'>" + dr["Factor"].ToString() + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";' width='3%'>" + dr["Pack1"].ToString() + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";' width='3%'>" + dr["remark"].ToString() + "</td>"); //备注
            strHtml.Append("<td style='color:" + forecolor + ";'>" + dr["QualityLevels"].ToString() + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";'>" + SysFun.OutNum(dr["BidPrice"].ToString(), 3) + "</td>");
            if (dr["DealStatus"].ToString() != "" && dr["DealStatus"].ToString() != "已入库")
            {

                switch (pricestatus)
                {
                    case 0:   //  固定,默认为挂网价
                        strHtml.Append("<td><input type='hidden' name='oldTradePrice' value='" + dr["TradePrice"].ToString() + "' /><input type='hidden' name='buyplangoodsid' value='" + dr["BuyPlanGoodsId"].ToString() + "' /><input type='hidden' name='BidPrice' value='" + SysFun.OutNum(dr["BidPrice"].ToString(), 3) + "'>" +
                                "<input type='text' readonly='true' size=8 name='TradePrice' onblur=\"javascript:if(!/^[0-9]+(\\.[0-9]{1,3})?$/.test(this.value)){alert('流水号" + dr["GoodsId"].ToString() + "请输入正确价格！');this.value=" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "};if(this.value>" + SysFun.OutNum(dr["BidPrice"].ToString(), 3) + "){alert('流水号" + dr["GoodsId"].ToString() + "输入价格不能大于挂网价格！');this.value=" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "}\" NumericOnly='TradePrice' NotNull='TradePrice'  value='" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "'title='挂网价为：" + Math.Round(double.Parse(dr["BidPrice"].ToString()), 3) + "'  BorderStyle=\"None\" ></td>");
                        break;
                    case 1:   //  可修改,必须低于挂网价

                        strHtml.Append("<td><input type='hidden' name='oldTradePrice' value='" + dr["TradePrice"].ToString() + "' /><input type='hidden' name='buyplangoodsid' value='" + dr["BuyPlanGoodsId"].ToString() + "' /><input type='hidden' name='BidPrice' value='" + SysFun.OutNum(dr["BidPrice"].ToString(), 3) + "'>" +
                               "<input type='text' size=8 name='TradePrice' onblur=\"javascript:if(!/^[0-9]+(\\.[0-9]{1,3})?$/.test(this.value)){alert('流水号" + dr["GoodsId"].ToString() + "请输入正确价格！');this.value=" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "};if(this.value>" + SysFun.OutNum(dr["BidPrice"].ToString(), 3) + "){alert('流水号" + dr["GoodsId"].ToString() + "输入价格不能大于挂网价格！');this.value=" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "}\" NumericOnly='TradePrice' NotNull='TradePrice'  value='" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "'title='挂网价为：" + Math.Round(double.Parse(dr["BidPrice"].ToString()), 3) + "'  BorderStyle=\"None\" ></td>");
                        break;
                    case 2:   //  可修改,无限制

                        strHtml.Append("<td><input type='hidden' name='oldTradePrice' value='" + dr["TradePrice"].ToString() + "' /><input type='hidden' name='buyplangoodsid' value='" + dr["BuyPlanGoodsId"].ToString() + "' /><input type='hidden' name='BidPrice' value='" + SysFun.OutNum(dr["BidPrice"].ToString(), 3) + "'>" +
                                "<input type='text'  size=8 name='TradePrice' onblur=\"javascript:if(!/^[0-9]+(\\.[0-9]{1,3})?$/.test(this.value)){alert('流水号" + dr["GoodsId"].ToString() + "请输入正确价格！');this.value=" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "};this.value=" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "}\" NumericOnly='TradePrice' NotNull='TradePrice'  value='" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "'title='挂网价为：" + Math.Round(double.Parse(dr["BidPrice"].ToString()), 3) + "'   BorderStyle=\"None\" ></td>");
                        break;
                }
                if (dr["DealStatus"].ToString().Contains("送货中") || dr["DealStatus"].ToString().Contains("未确认"))
                {
                    strHtml.Append("<td><input type='hidden' name='oldGoodsNum' value='" + dr["GoodsNum"].ToString() + "' /><input type='text' size=8  name='GoodsNum' onblur=\"javascript:if(!/^\\d+$/.test(this.value)){alert('流水号" + dr["GoodsId"].ToString() + "请输入正确的数量！');this.value=" + SysFun.ToDouble(SysFun.ToTrim(dr["GoodsNum"])) + "} \" NumericOnly='GoodsNum' NotNull='GoodsNum'  value='" + SysFun.ToTrim(dr["GoodsNum"]) + "' ></td>");

                }
                else
                {
                    strHtml.Append("<td><input type='hidden' name='oldGoodsNum' value='" + dr["GoodsNum"].ToString() + "' /><input type='hidden'  name='GoodsNum'   value='" + SysFun.ToTrim(dr["GoodsNum"]) + "' >" + SysFun.ToTrim(dr["GoodsNum"]) + "</td>");
                }
            }
            else
            {
                strHtml.Append("<td style='color:" + forecolor + ";'>" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "</td>");
                strHtml.Append("<td style='color:" + forecolor + ";'>" + SysFun.ToTrim(dr["GoodsNum"]) + "</td>");
            }
            strHtml.Append("<td style='color:" + forecolor + ":'><input type='hidden' name='InflowNum' id='InflowNum' value='" + SysFun.ToTrim(dr["InflowNum"]) + "'>" + SysFun.ToTrim(dr["InflowNum"]) + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";'>" + SysFun.OutNum(dr["PurchasePrice"].ToString(), 3) + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";'><input type='hidden' name='pricestatus' id='pricestatus' value='" + pricestatus + "'><input type='hidden' name='AccountId_PS' value='" + dr["AccountId_PS"].ToString() + "' />" + dr["CompanyName_SC"].ToString() + "</td>");
            strHtml.Append("<td style='color:" + forecolor + ";'>" + dr["CompanyName_PS"].ToString() + "</td>");
            //if (dr["DealStatus"].ToString() == "企业无法送货")
            //{
            //    strHtml.Append("<td ><a href=# onClick=\"javascript:window.open('../Bidder/TraNoPS.aspx?BId=" + dr["BuyPlanGoodsId"].ToString() + "','','width=670,height=250,toolbar=no, status=no, menubar=no, resizable=yes, scrollbars=yes');return false;\" target='_blank'><font color='ff0000'>" + dr["DealStatus"].ToString() + "</font></a></td>");
            //}
            //else
            //{
            strHtml.Append("<td style='color:" + forecolor + ";'>" + dr["DealStatus"].ToString() + "</td>");
            //}5
            //strHtml.Append("<td style='color:" + forecolor + ";'>" + dr["GoodsState"].ToString() + "</td>");


            if (dr["DealStatus"].ToString().Contains("送货中") || dr["DealStatus"].ToString().Contains("未确认"))
            {
                strHtml.Append("<td><input name='chk' type='checkbox' value='" + dr["BuyPlanGoodsId"].ToString() + "'></td>");
            }
            else
            {
                strHtml.Append("<td>&nbsp;</td>");
            }
            strHtml.Append("</tr>");
        }

        strHtml.Append("</table>");
        Lablist.Text = strHtml.ToString();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键

    }

    /// <summary>
    /// 查询条件:'0'表示'页面显示'; '1'表示'打印'
    /// </summary>
    /// <param name="nI"></param>
    /// <returns></returns>
    private string strcheck(int nI)
    {

        string _strTemp = "";
        string _strGoodsId, _strProductName, _strCompanyName_SC, _strCompanyName_SC_usercoder, _strCompanyName_PS, _strCompanyname_PS_usercoder, _strGoodsName;

        if (nI == 0)
        {
            _strTemp = " buyplanid=" + BuyPlanId + " and  BuyGoodsView_200708.S_GProjectid=project.projectid and (CompanyName_ps is not null and CompanyName_ps<>'') and Accountid_YY=" + Accountid_yy + " ";
        }
        else
        {
            _strTemp = " buyplanid=" + BuyPlanId + " and   BuyGoodsView_200708.S_GProjectid=project.projectid and (CompanyName_ps is not null and CompanyName_ps<>'') and Accountid_YY=" + Accountid_yy;
        }


        //商品流水号
        _strGoodsId = txtGoodsId.Text.ToString();
        if (_strGoodsId != "")
        {
            _strTemp += " and GoodsId =" + _strGoodsId;
        }

        //商品名
        _strGoodsName = txtGoodsName.Text.ToString();
        if (_strGoodsName != "")
        {
            _strTemp += " and GoodsName like '%" + _strGoodsName + "%'";
        }

        //药品名称或拼音码
        _strProductName = txtProductName.Text.ToString().Trim();
        if (_strProductName != "")
        {
            _strTemp = _strTemp + " and (ProductName like '%" + _strProductName + "%' or Product_SpellingCode like '%" + _strProductName + "%')";
        }

        //生产企业名称
        _strCompanyName_SC = textCompanyName_SC.Text.ToString().Trim();
        if (_strCompanyName_SC != "")
        {
            _strTemp = _strTemp + " and CompanyName_SC like '%" + _strCompanyName_SC + "%'";
        }
        //生产企业编码
        _strCompanyName_SC_usercoder = Textuscoder_sc.Text.ToString().Trim();
        if (_strCompanyName_SC_usercoder != "")
        {
            _strTemp = _strTemp + " and UserCode_SC like '%" + _strCompanyName_SC_usercoder + "%'";
        }


        //配送企业名称

        _strCompanyName_PS = TextCompanyName_PS.Text.ToString().Trim();
        if (_strCompanyName_PS != "")
        {
            if ((string)ViewState["buystateg"] == "2")
            {
                _strTemp = _strTemp + " and CompanyName_PS like '%" + _strCompanyName_PS + "%'";
            }
            else
            {
                _strTemp = _strTemp + " and SupplyCompany.CompanyName_PS like '%" + _strCompanyName_PS + "%'";
            }

        }
        //配送企业编码

        _strCompanyname_PS_usercoder = Textuscoder_ps.Text.ToString().Trim();
        if (_strCompanyname_PS_usercoder != "")
        {
            if ((string)ViewState["buystateg"] == "2")
            {
                _strTemp = _strTemp + " and UserCode_PS like '%" + _strCompanyname_PS_usercoder + "%'";
            }
            else
            {
                _strTemp = _strTemp + " and SupplyCompany.UserCode_PS like '%" + _strCompanyname_PS_usercoder + "%'";
            }

        }

        //采购数量
        string _strGoodsNum = txtGoodsNum.Text.ToString();
        if (_strGoodsNum != "")
        {
            if (_strGoodsNum == "0")
            {
                _strTemp = _strTemp + " and (GoodsNum=0 or GoodsNum is null) ";
            }
            else
            {
                _strTemp = _strTemp + " and GoodsNum=" + _strGoodsNum;
            }
        }
        return _strTemp;
    }

    /// <summary>
    /// 到期未送货
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button3_Click(object sender, EventArgs e)
    {

        string BuyPlanGoodsId = "";
        BuyPlanGoodsId = SysFun.ToTrim(Request.Form["chk"]);

        Db db = new Db();
        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
        if (BuyPlanGoodsId != "")
        {

            string[] SGID = BuyPlanGoodsId.Length == 0 ? new string[] { "" } : BuyPlanGoodsId.Substring(0).Split(new char[] { ',' });
            strSql = "";
            for (int i = 0; i < SGID.Length; i++)
            {

                strSql += "@" + "update BuyPlanGoods set dealstatus=5 where BuyPlanGoodsId  =" + SGID[i].ToString() + " and dealstatus=1 ";

            }
            if (strSql.Length > 0)
            {

                db.ExecuteTransaction(strSql.Substring(1).Split(new char[] { '@' }), 30);
                HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "BuyPlanGoods", strSql, "../Hospital/PurchaseDeal_detail.aspx");

            }

        }


        Response.Write("<script>window.opener.location.reload();window.close();</script>");
        db.Close();

    }

    /// <summary>
    /// 绑定采购单
    /// </summary>
    private void CopyPurchasePlan()
    {

        string strSele = "select top 10 buyplanid,planname from PurchasePlan where buyplanid<>" + BuyPlanId + " and accountid_yy=" + Accountid_yy + " order by buildtime desc ";
        Db db = new Db();
        DataTable dt = db.DataTable(strSele);
        db.Close();
        if (dt.Rows.Count > 0)
            PurchasePlanSele.DataSource = dt;

        PurchasePlanSele.DataTextField = "planname";
        PurchasePlanSele.DataValueField = "buyplanid";
        PurchasePlanSele.DataBind();

    }

    protected void ConfirmNum_Click(object sender, EventArgs e)
    {

        string BuyPlanGoodsId = "", caigoushu;
        BuyPlanGoodsId = SysFun.ToTrim(Request.Form["buyplangoodsid"]);
        caigoushu = Request.Form["GoodsNum"];
        Db db = new Db();

        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];

        if (BuyPlanGoodsId != "")
        {
            string[] SGID = BuyPlanGoodsId.Length == 0 ? new string[] { "" } : BuyPlanGoodsId.Substring(0).Split(new char[] { ',' });
            string[] CNum = caigoushu.Length == 0 ? new string[] { "" } : caigoushu.Substring(0).Split(new char[] { ',' });
            strSql = "";
            for (int i = 0; i < SGID.Length; i++)
            {

                strSql += "@" + "update BuyPlanGoods set GoodsNum=" + SysFun.ToInt(CNum[i]) + ",PurchasePrice=TradePrice*" + SysFun.ToInt(CNum[i]) + " where BuyPlanGoodsId=" + SGID[i].ToString();
            }

        }
        HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "BuyPlanGoods", strSql, "../Hospital/PurchaseDeal_detail.aspx"); ;
        Response.Write("<script>window.opener.location.reload();window.close();</script>");
        db.Close();

    }

    /// <summary>
    /// 打印采购明细
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button2_ServerClick(object sender, EventArgs e)
    {

        //0 原挂网商品
        //1 自行采购
        //2  22种降价药
        //3 人血蛋白
        //4 重点监控
        //默认为‘0’

        Db db = new Db();
        string StrSql;
        System.Data.IDataReader dr;
        //  StrSql = @"select GoodsId as 商品流水号,ProductName as 通用名,GoodsName as 商品名,MedicineModel as 剂型,Outlookc as 规格,Factor 转换系数,IsNull(Unit,'')+'/'+IsNull(PackUnit,'') As 包装规格,
        //  case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " END as 质量层次,BidPrice as 挂网价,TradePrice as 交易价,GoodsNum as 采购量,PurchasePrice as 采购总金额 ,CompanyName_SC as 生产企业,CompanyName_PS as 配送企业, Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '送货中' WHEN '2' then '已入库' WHEN '3' then '退货' When '4' Then '企业无法送货' When '5' Then '已确认到期未送货' When '6' Then '已删除' END AS 交易状态, Case GoodsState When '0' Then '原挂网' WHEN '1' Then '自行采购' WHEN '2' then '22种降价药' when '3' then '血液制品' when '4' then '重点监控'  END AS 采购目录状态  from dbo.BuyGoodsView_200708 ,project where " + strcheck(1) + " order by goodsid,ProductName,MedicineModel";
        StrSql = @"select GoodsId as 商品流水号,ProductName as 通用名,GoodsName as 商品名,MedicineModel as 剂型,Outlookc+'×'+convert(varchar(20),Factor)+unit As 包装规格,remark as 备注,
                   case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " END as 质量层次,BidPrice as 挂网价,TradePrice as 交易价,GoodsNum as 采购量,PurchasePrice as 采购总金额 ,CompanyName_SC as 生产企业,CompanyName_PS as 配送企业, Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '送货中' WHEN '2' then '已入库' WHEN '3' then '退货' When '4' Then '企业无法送货' When '5' Then '已确认到期未送货' When '6' Then '已删除' END AS 交易状态  from dbo.BuyGoodsView_200708 ,project where " + strcheck(1) + " order by goodsid,ProductName,MedicineModel";
        dr = db.DataReader(StrSql);
        this.GridView1.DataSource = dr;
        this.GridView1.DataBind();
        db.Close();
        dr.Close();
        dr.Dispose();

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        // 添加头信息，为"文件下载/另存为"对话框指定默认文件名 
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("采购明细.xls"));

        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = "application/ms-excel";
        this.EnableViewState = false;
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        this.GridView1.RenderControl(oHtmlTextWriter);

        // 把文件流发送到客户端 
        Response.Write(oStringWriter.ToString());
        // 停止页面的执行


        Response.End();
    }

    protected void CopyPland_Click(object sender, EventArgs e)//复制采购单
    {
        Db db = new Db();
        DataTable dt = db.DataTable("select * from BuyPlanGoods where buyplanid=" + BuyPlanId);
        db.Close();
        if (dt.Rows.Count > 0)
        {
            Response.Write("<script>alert('当前采购单已采购药品，不让复制！')</script>");
        }
        else
        {
            int succ = 0;
            SqlParameter[] param = new SqlParameter[4];
            param[0] = new SqlParameter("@BuyPlanIdin", BuyPlanId);
            param[1] = new SqlParameter("@BuyPlanIdfrom", PurchasePlanSele.SelectedValue);
            param[2] = new SqlParameter("@accountid_yy", Accountid_yy);
            param[3] = new SqlParameter("@V_Succ", succ);
            param[3].Direction = ParameterDirection.Output;
            db = new Db();
            db.ExecuteProcedure("P_InsertBuyPlanGoods", param);
            db.Close();
            succ = (int)param[3].Value;
            if (succ == 1)
            {
                Response.Write("<script>alert('复制成功!');self.close();</script>");
            }
            else
            {
                Response.Write("<script>alert('复制失败!');self.close();</script>");
            }

        }
    }


}

